package com.xiaomuwu.android.ui.home

import androidx.fragment.app.Fragment
import androidx.viewpager2.adapter.FragmentStateAdapter

class ContentAdapter(fragment: Fragment): FragmentStateAdapter(fragment) {

    private val fragments=HashMap<Int, Fragment>()

    init{
        fragments[PAGE_RESOURCE] = ResFragment() //check
        fragments[PAGE_USER] = UserFragment() //check
    }

    override fun getItemCount():Int{
        return fragments.size
    }

    override fun createFragment(position: Int): Fragment {
        lateinit var fragment: Fragment
        when(position){
            PAGE_RESOURCE -> {
                if (fragments[PAGE_RESOURCE] == null) {
                    fragment = ResFragment()
                    fragments[PAGE_RESOURCE] = fragment
                } else {
                    fragment = fragments[PAGE_RESOURCE]!!   //check(!!)
                }
            }
            PAGE_USER -> {
                if (fragments[PAGE_USER] == null) {
                    fragment = UserFragment()
                    fragments[PAGE_USER] = fragment
                } else {
                    fragment = fragments[PAGE_USER]!!    //check(!!)
                }
            }
        }
        return fragment
    }

    companion object {
        const val PAGE_RESOURCE=0
        const val PAGE_USER=1
    }

}